import React, { useCallback, useEffect, useRef, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
// 顶部的无限滚动
function InfiniteScrollTopPage() {
    const [items, setItems] = useState<any[]>([]);
    const [hasMore, setHasMore] = useState<boolean>(true);
    const containerRef = useRef<HTMLDivElement | null>(null);
    useEffect(() => {
        const mockData = [...new Array(100)].map((_, index) => ({ id: index, name: `item_${index}` }));
        setItems(mockData);
    }, []);

    // 加载更多数据
    const fetchMoreData = useCallback(function fetchMoreData() {
        setTimeout(() => {
            setItems((preItems) => {
                const mockData = [...new Array(100)].map((_, index) => ({
                    id: preItems.length + index,
                    name: `item_${preItems.length + index}`,
                }));
                return [...preItems, ...mockData];
            });
            setHasMore(false);
        }, 2000);
    }, []);

    return (
        <div className='h-full w-full overflow-auto flex flex-col-reverse' ref={containerRef}>
            {/* Put the scroll bar always on the bottom */}
            {containerRef.current && (
                <InfiniteScroll
                    dataLength={items.length}
                    next={fetchMoreData}
                    className='flex flex-col-reverse'
                    inverse //
                    hasMore={hasMore}
                    loader={<div className='h-8 w-full flex items-center justify-center'>加载中...</div>}
                    endMessage={<div className='h-8 w-full flex items-center justify-center'>没有更多数据了</div>}
                    scrollableTarget={containerRef.current as any}
                >
                    {items.map((item) => (
                        <div className='h-8 w-full flex items-center border-solid border-gray-50 px-4' key={item.id}>
                            div - #{item.name}
                        </div>
                    ))}
                </InfiniteScroll>
            )}
        </div>
    );
}

export default InfiniteScrollTopPage;
